package com.hst.capacity.facade.rest;


import cn.hutool.core.util.StrUtil;
import com.hst.capacity.application.biz.InvoiceBiz;
import com.hst.capacity.application.biz.TokenBiz;
import com.hst.capacity.application.mail.MailService;
import com.hst.capacity.domain.common.constants.Constants;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.request.invoice.InvoiceLstParam;
import com.hst.capacity.domain.model.request.invoice.InvoiceParam;
import com.hst.capacity.domain.model.response.DefaultVO;
import com.hst.capacity.domain.service.UploadService;
import com.qiniu.storage.model.DefaultPutRet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import static com.hst.capacity.domain.model.response.DefaultVO.success;

@Slf4j
@RequestMapping("/invoice")
@RestController
public class InvoiceController {

    @Autowired
    InvoiceBiz invoiceBiz;

    @Autowired
    TokenBiz tokenBiz;

    @Autowired
    private UploadService uploadService;

    /**
     * 发票数据取得
     * @param
     * @return
     */
    @PostMapping("/list")
    private DefaultVO findInvoiceLst(@RequestBody @Valid InvoiceLstParam param, HttpServletRequest request) {
        param.setIdFinance(tokenBiz.findIdUser(request));
        return success(invoiceBiz.findInvoiceLst(param));
    }

    /**
     * 发票详细数据取得
     * @param
     * @return
     */
    @PostMapping("/detail/id")
    private DefaultVO findByIdInvoice(@RequestBody Map<String,String> param) {
        String idInvoice = param.get("idInvoice");
        if (StrUtil.isEmpty(idInvoice))
            throw new BusinessException(4001,"发票主键[idInvoice]不能为空");
        return success(invoiceBiz.findByIdInvoice(idInvoice));
    }

    /**
     * 发票详细数据取得
     * @param
     * @return
     */
    @PostMapping("/detail/id-order")
    private DefaultVO findByIdOrder(@RequestBody Map<String,String> param) {
        String idOrder = param.get("idOrder");
        if (StrUtil.isEmpty(idOrder))
            throw new BusinessException(4001,"订单[idOrder]不能为空");
        return success(invoiceBiz.findByIdOrder(idOrder));
    }

    /**
     * 更新上传发票信息
     * @return
     */
    @PostMapping("/upload/file")
    private DefaultVO uploadFile(@RequestParam("idInvoice")String idInvoice, @RequestParam("file") MultipartFile multipartFile) {
        //String idInvoice = param.get("idInvoice");
        if (StrUtil.isEmpty(idInvoice))
            throw new BusinessException(4001,"订单[idInvoice]不能为空");
        String subPath = Constants.Invoice_Pdf_Path;
        if (multipartFile.isEmpty()) {
            throw new BusinessException(4001,"参数异常，文件内容异常。");
        }
        // 当文件超过设置的大小时2M暂定，则不运行上传
        if (multipartFile.getSize() > Constants.FILE_SIZE) {
            throw new BusinessException(4001,"文件异常，文件过大。");
        }
        // 获取文件名后缀
        String OriginalFilename = multipartFile.getOriginalFilename();
        String fileSuffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();

        String newFileName = new Date().getTime() + ".";

        newFileName += fileSuffix; // 追加后缀
        newFileName = subPath + "/" + newFileName;
        // 判断该类型的文件是否在允许上传的文件类型内
        if (!Arrays.asList(Constants.TYPE_MAP.get("invoice").split(",")).contains(fileSuffix)) {
            throw new BusinessException(4001,"文件类型不对");
        }
        DefaultPutRet updRet = uploadService.uploadImage(newFileName, multipartFile);

        invoiceBiz.saveInvoicePdf(idInvoice, updRet.key);

        try {
            invoiceBiz.sendMail(idInvoice);
        } catch (Exception e) {
            log.info("发送邮件失败：｛｝", idInvoice);
        }

        return success(updRet);
    }

    /**
     * 更新发票信息
     * @param
     * @return
     */
    @PostMapping("/update")
    private DefaultVO updInvoice(@RequestBody InvoiceParam param) {
        return success(invoiceBiz.updInvoiceInfo(param));
    }

    /**
     * 发票作废
     * @param
     * @return
     */
    @PostMapping("/invalid")
    private DefaultVO invalidInvoice(@RequestBody InvoiceParam param) {
        return success(invoiceBiz.invalidInvoice(param));
    }

    /**
     * 发票文件本地上传
     * @return
     */
    @PostMapping("/upload")
    private DefaultVO uploadInvoiceFile(@RequestParam("type")int type, @RequestParam("file") MultipartFile multipartFile) {
        // String subPath;
        // if (StrUtil.isEmpty(subPath = param.get("subPath")))throw new BusinessException(4003,"图片路径[subPath]不能为空");
//        String subPath = Constants.Image_Path_Type.get(type);
//        if (multipartFile.isEmpty()) {
//            throw new BusinessException(4001,"参数异常，文件内容异常。");
//        }
//        // 当文件超过设置的大小时2M暂定，则不运行上传
//        if (multipartFile.getSize() > Constants.FILE_SIZE) {
//            throw new BusinessException(4001,"文件异常，文件过大。");
//        }
//        // 获取文件名后缀
//        String OriginalFilename = multipartFile.getOriginalFilename();
//        String fileSuffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
//
//        String newFileName = new Date().getTime() + ".";
//
//        newFileName += fileSuffix; // 追加后缀
//        newFileName = subPath + "/" + newFileName;
//        // 判断该类型的文件是否在允许上传的文件类型内
//        if (!Arrays.asList(Constants.TYPE_MAP.get("image").split(",")).contains(fileSuffix)) {
//            throw new BusinessException(4001,"图片路径[subPath]不能为空");
//        }
//        DefaultPutRet updRet = uploadService.uploadImage(newFileName, multipartFile);
//
//        return success(updRet);
        return null;
    }

    /**
     * 发票作废
     * @param
     * @return
     */
    @PostMapping("/send/mail")
    private DefaultVO sendMail(@RequestBody InvoiceParam param) {
        return success(invoiceBiz.sendMail(param));
    }

}
